<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { useUserState } from "../store";
import router from "../config/route";
import { userLoginUsingPost } from "../servers/user/api/userController";

const { setUserState, getLoginUserState } = useUserState();

const ruleFormRef = ref<FormInstance>();
const loginFormRules = {
  userAccount: [{ required: true, message: "请输入账号", trigger: "blur" }],
  userPassword: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

const loginForm = reactive({
  userAccount: "",
  userPassword: "",
});

const submitForm = async () => {
  // 用户登录
  console.log("用户登录");
  const { data } = await userLoginUsingPost({ ...loginForm });
  // 保存用户态
  if (data.code === 200) {
    setUserState(data.data!);
    ElMessage.success("用户成功登录");
    // 登录成功，跳转到主页
    await router.push("/");
  } else {
    ElMessage.error("登录失败：" + data.message);
  }
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 页面挂载完成执行
onMounted(() => {
  getLoginUserState();
});
</script>

<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="loginForm"
    status-icon
    :rules="loginFormRules"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="账户" prop="userAccount">
      <el-input v-model="loginForm.userAccount" autocomplete="off" />
    </el-form-item>
    <el-form-item label="密码" prop="userPassword">
      <el-input
        v-model="loginForm.userPassword"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm()"> Submit</el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>
